const storage = require('../../utils/storage.js');
const api = require('../../utils/api.js');
const imageUtil = require('../../utils/image.js');

Page({
  data: {
    statusBarHeight: 0,
    navBarHeight: 0,
    // 编辑数据
    editData: {
      nickname: '用户0876',
      avatar: '/images/icons/avatar.png',
      gender: '未知',
      age: 0,
      birthday: '',
      signature: '这个人很懒，什么都没留下',
      location: '未知',
      photos: []
    },
    // 爱好列表
    hobbies: [
      { id: 1, name: '吃', selected: false },
      { id: 2, name: '喝', selected: false },
      { id: 3, name: '玩', selected: false },
      { id: 4, name: '乐', selected: false },
      { id: 5, name: '购', selected: false }
    ],
    // 弹窗控制
    showNicknameModal: false,
    showSignatureModal: false,
    showLocationModal: false,
    showGenderModal: false,
    // 性别选项
    genderOptions: ['男', '女', '未知'],
    // 临时输入值
    tempNickname: '',
    tempSignature: '',
    tempLocation: ''
  },

  onLoad(options) {
    const windowInfo = wx.getWindowInfo();
    const navBarHeight = windowInfo.statusBarHeight + 44; // 44px 转换为实际像素
    this.setData({
      statusBarHeight: windowInfo.statusBarHeight,
      navBarHeight: navBarHeight
    });
    
    // 加载用户信息
    this.loadUserInfo();
  },

  onShow() {
    // 🔔 自动初始化通知组件
    const app = getApp();
    app.autoInitNotification();
  },

  // 加载用户信息
  loadUserInfo() {
    const userData = storage.getUserInfo();
    if (userData) {
      console.log('📊 加载编辑页用户信息:', userData);
      
      // 🔍 调试：检查 openid 是否正确加载
      console.log('🔍 调试 loadUserInfo - extraData:', userData.extraData);
      console.log('🔍 调试 loadUserInfo - openid路径1:', userData?.extraData?.openid);
      console.log('🔍 调试 loadUserInfo - openid路径2:', userData?.openid);
      console.log('🔍 调试 loadUserInfo - wx_openid缓存:', wx.getStorageSync('wx_openid'));
      
      // 处理爱好数据
      const userHobbies = userData.userHobbies || [];
      const hobbies = this.data.hobbies.map(item => {
        return {
          ...item,
          selected: userHobbies.includes(item.name)
        };
      });
      
      // 🔥 处理照片数据 - 将HTTP转HTTPS（真机要求）
      const photos = userData.userImgUrls || [];
      const photosHttps = imageUtil.toHttpsArray(photos, '/images/icons/avatar.png');
      
      console.log('📸 原始相册图片:', photos);
      console.log('📸 转换后相册图片:', photosHttps);
      
      this.setData({
        editData: {
          nickname: userData.username || '用户',
          avatar: imageUtil.processAvatar(userData.userAvatarUrl), // 🔥 使用图片工具类处理头像
          gender: userData.userGender || '未知',
          age: userData.userAge || 0,
          birthday: userData.userBirthday || '',
          signature: userData.userSignature || '这个人很懒，什么都没留下',
          location: userData.userFrequentPlaces || '未知',
          photos: photosHttps // 🔥 使用转换后的HTTPS图片数组
        },
        hobbies: hobbies
      });
    } else {
      console.warn('⚠️ 未找到用户信息');
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      });
      setTimeout(() => {
        wx.reLaunch({
          url: '/pages/login/index'
        });
      }, 2000);
    }
  },

  // 返回
  goBack() {
    wx.navigateBack();
  },

  // 选择并上传头像（参考Flutter项目的实现）
  chooseAvatar() {
    const userData = storage.getUserInfo();
    if (!userData || !userData.userid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0];
        console.log('📸 选择的头像路径:', tempFilePath);

        try {
          // 显示上传提示
          wx.showLoading({
            title: '上传中...',
            mask: true
          });

          // 🔥 步骤1: 上传图片到服务器，获取URL（参考Flutter的uploadUserAvatar）
          const uploadResult = await api.uploadUserImage(userData.userid, tempFilePath);
          
          if (uploadResult.status === 'success' && uploadResult.image_url) {
            console.log('✅ 头像上传成功，URL:', uploadResult.image_url);
            
            // 🔥 步骤2: 更新本地显示（先显示，提升用户体验）
            this.setData({
              'editData.avatar': uploadResult.image_url
            });

            // 🔥 步骤3: 调用update接口同步到服务器（参考Flutter的实现）
            const updateData = {
              userPhone: userData.userPhone,
              userAvatarUrl: uploadResult.image_url
            };

            await api.updateUserInfo(updateData);
            console.log('✅ 头像URL已同步到服务器');

            // 🔥 步骤4: 更新本地用户信息（保留 extraData）
            const updatedUserData = {
              ...userData,
              userAvatarUrl: uploadResult.image_url,
              // 🔥 确保 extraData（包含 openid）被保留
              extraData: {
                ...(userData.extraData || {}),
                openid: userData?.extraData?.openid || wx.getStorageSync('wx_openid')
              }
            };
            storage.saveUserInfo(updatedUserData);
            
            console.log('🔍 调试 chooseAvatar - 保存的 openid:', updatedUserData.extraData?.openid);

            wx.hideLoading();
            wx.showToast({
              title: '头像更新成功',
              icon: 'success'
            });

          } else {
            throw new Error(uploadResult.message || '上传失败');
          }

        } catch (error) {
          wx.hideLoading();
          console.error('❌ 上传头像失败:', error);
          wx.showToast({
            title: '上传失败，请重试',
            icon: 'none'
          });
        }
      }
    });
  },

  // 显示昵称输入
  showNicknameInput() {
    this.setData({
      showNicknameModal: true,
      tempNickname: this.data.editData.nickname
    });
  },

  // 昵称输入
  onNicknameInput(e) {
    this.setData({
      tempNickname: e.detail.value
    });
  },

  // 🔒 保存昵称（添加内容安全检测）
  async saveNickname() {
    const nickname = this.data.tempNickname.trim();
    
    // 验证昵称不能为空
    if (!nickname) {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none'
      });
      return;
    }

    // 🔒 内容安全检测
    const userData = storage.getUserInfo();
    
    // 🔍 调试：打印用户数据结构
    console.log('🔍 调试 saveNickname - userData:', userData);
    console.log('🔍 调试 saveNickname - extraData:', userData?.extraData);
    console.log('🔍 调试 saveNickname - openid路径1:', userData?.extraData?.openid);
    console.log('🔍 调试 saveNickname - openid路径2:', userData?.openid);
    
    const openid = userData?.extraData?.openid || userData?.openid;
    
    console.log('🔍 最终获取的 openid:', openid);
    
    if (openid) {
      try {
        wx.showLoading({
          title: '检测中...',
          mask: true
        });

        const checkResult = await api.checkContentSecurity(
          nickname,
          openid,
          1, // 场景：1=资料
          { nickname: nickname }
        );

        wx.hideLoading();

        const suggest = checkResult.result.suggest;
        
        if (suggest === 'risky') {
          // 内容违规，禁止保存
          wx.showModal({
            title: '内容违规',
            content: checkResult.result.message || '昵称包含违规信息，请修改',
            showCancel: false,
            confirmColor: '#D84545'
          });
          return;
        } else if (suggest === 'review') {
          // 需要审核，提示用户
          wx.showModal({
            title: '需要审核',
            content: '您的昵称需要审核，审核通过后将自动生效',
            confirmText: '确定',
            showCancel: false
          });
        }
        
        // pass 或 review 都允许保存
        this.setData({
          'editData.nickname': nickname,
          showNicknameModal: false
        });

      } catch (error) {
        wx.hideLoading();
        console.error('❌ 昵称内容检测失败:', error);
        
        // 检测失败降级处理：允许保存但提示
        wx.showModal({
          title: '提示',
          content: '内容检测服务暂时不可用，您的昵称将在审核后生效',
          confirmText: '继续',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              this.setData({
                'editData.nickname': nickname,
                showNicknameModal: false
              });
            }
          }
        });
      }
    } else {
      // 没有 openid，直接保存但记录警告
      console.warn('⚠️ 缺少openid，跳过内容安全检测');
      this.setData({
        'editData.nickname': nickname,
        showNicknameModal: false
      });
    }
  },

  // 显示性别选择
  showGenderPicker() {
    this.setData({
      showGenderModal: true
    });
  },

  // 选择性别
  selectGender(e) {
    const { value } = e.currentTarget.dataset;
    this.setData({
      'editData.gender': value,
      showGenderModal: false
    });
  },

  // 关闭性别选择
  closeGenderPicker() {
    this.setData({
      showGenderModal: false
    });
  },

  // 生日改变
  onBirthdayChange(e) {
    const birthday = e.detail.value;
    const age = this.calculateAge(birthday);
    this.setData({
      'editData.birthday': birthday,
      'editData.age': age
    });
  },

  // 计算年龄
  calculateAge(birthday) {
    if (!birthday) return 0;
    const birthDate = new Date(birthday);
    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }
    return age;
  },

  // 显示签名输入
  showSignatureInput() {
    this.setData({
      showSignatureModal: true,
      tempSignature: this.data.editData.signature
    });
  },

  // 签名输入
  onSignatureInput(e) {
    this.setData({
      tempSignature: e.detail.value
    });
  },

  // 🔒 保存签名（添加内容安全检测）
  async saveSignature() {
    const signature = this.data.tempSignature.trim();
    
    // 验证签名不能为空
    if (!signature) {
      wx.showToast({
        title: '签名不能为空',
        icon: 'none'
      });
      return;
    }

    // 🔒 内容安全检测（自动从 storage 读取 openid）
    const userData = storage.getUserInfo();
    
    try {
      wx.showLoading({
        title: '检测中...',
        mask: true
      });

      // 🔥 调用内容检测接口（自动从 storage 读取 openid）
      const checkResult = await api.checkContentSecurity(
        signature,
        1, // 场景：1=资料
        { 
          nickname: userData?.username || '用户',
          signature: signature
        }
      );

      wx.hideLoading();

      const suggest = checkResult.result.suggest;
      
      if (suggest === 'risky') {
        // 内容违规，禁止保存
        wx.showModal({
          title: '内容违规',
          content: checkResult.result.message || '签名包含违规信息，请修改',
          showCancel: false,
          confirmColor: '#D84545'
        });
        return;
      } else if (suggest === 'review') {
        // 需要审核，提示用户
        wx.showModal({
          title: '需要审核',
          content: '您的签名需要审核，审核通过后将自动生效',
          confirmText: '确定',
          showCancel: false
        });
      }
      
      // pass 或 review 都允许保存
      this.setData({
        'editData.signature': signature,
        showSignatureModal: false
      });

    } catch (error) {
      wx.hideLoading();
      console.error('❌ 签名内容检测失败:', error);
      
      // 检测失败降级处理：允许保存但提示
      wx.showModal({
        title: '提示',
        content: '内容检测服务暂时不可用，您的签名将在审核后生效',
        confirmText: '继续',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.setData({
              'editData.signature': signature,
              showSignatureModal: false
            });
          }
        }
      });
    }
  },

  // 显示常出没地输入
  showLocationInput() {
    this.setData({
      showLocationModal: true,
      tempLocation: this.data.editData.location
    });
  },

  // 常出没地输入
  onLocationInput(e) {
    this.setData({
      tempLocation: e.detail.value
    });
  },

  // 保存常出没地
  saveLocation() {
    this.setData({
      'editData.location': this.data.tempLocation,
      showLocationModal: false
    });
  },

  // 关闭输入弹窗
  closeInputModal() {
    this.setData({
      showNicknameModal: false,
      showSignatureModal: false,
      showLocationModal: false
    });
  },

  // 切换爱好
  toggleHobby(e) {
    const { id } = e.currentTarget.dataset;
    const hobbies = this.data.hobbies.map(item => {
      if (item.id === id) {
        return { id: item.id, name: item.name, selected: !item.selected };
      }
      return item;
    });
    this.setData({ hobbies });
  },

  // 添加照片（参考Flutter项目的uploadAlbumImage实现）
  addPhoto() {
    const userData = storage.getUserInfo();
    if (!userData || !userData.userid) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const currentLength = this.data.editData.photos.length;
    if (currentLength >= 4) {
      wx.showToast({ title: '最多4张照片', icon: 'none' });
      return;
    }

    wx.chooseImage({
      count: 4 - currentLength,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        console.log('📸 选择了相册图片，共', res.tempFilePaths.length, '张');
        
        try {
          wx.showLoading({
            title: '上传中...',
            mask: true
          });

          const uploadedUrls = [];
          
          // 🔥 步骤1: 逐个上传图片到服务器（参考Flutter的uploadAlbumImage）
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            const tempFilePath = res.tempFilePaths[i];
            console.log(`📤 上传第${i + 1}张图片:`, tempFilePath);
            
            const uploadResult = await api.uploadUserImage(userData.userid, tempFilePath);
            
            if (uploadResult.status === 'success' && uploadResult.image_url) {
              console.log(`✅ 第${i + 1}张图片上传成功:`, uploadResult.image_url);
              uploadedUrls.push(uploadResult.image_url);
            } else {
              console.error(`❌ 第${i + 1}张图片上传失败`);
            }
          }

          if (uploadedUrls.length > 0) {
            // 🔥 步骤2: 更新相册列表（添加到现有相册）
            const newPhotos = [...this.data.editData.photos, ...uploadedUrls];
            
            this.setData({
              'editData.photos': newPhotos
            });

            // 🔥 步骤3: 调用update接口同步相册到服务器
            const updateData = {
              userPhone: userData.userPhone,
              userImgUrls: newPhotos
            };

            await api.updateUserInfo(updateData);
            console.log('✅ 相册已同步到服务器');

            // 🔥 步骤4: 更新本地用户信息（保留 extraData）
            const updatedUserData = {
              ...userData,
              userImgUrls: newPhotos,
              // 🔥 确保 extraData（包含 openid）被保留
              extraData: {
                ...(userData.extraData || {}),
                openid: userData?.extraData?.openid || wx.getStorageSync('wx_openid')
              }
            };
            storage.saveUserInfo(updatedUserData);
            
            console.log('🔍 调试 addPhoto - 保存的 openid:', updatedUserData.extraData?.openid);

            wx.hideLoading();
            wx.showToast({
              title: `成功添加${uploadedUrls.length}张照片`,
              icon: 'success'
            });
          } else {
            throw new Error('所有图片上传失败');
          }

        } catch (error) {
          wx.hideLoading();
          console.error('❌ 添加相册图片失败:', error);
          wx.showToast({
            title: '上传失败，请重试',
            icon: 'none'
          });
        }
      }
    });
  },

  // 删除照片（同步到服务器）
  async deletePhoto(e) {
    const userData = storage.getUserInfo();
    if (!userData) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    const { index } = e.currentTarget.dataset;
    
    // 显示确认对话框
    const confirmed = await new Promise((resolve) => {
      wx.showModal({
        title: '确认删除',
        content: '确定要删除这张照片吗？',
        success: (res) => {
          resolve(res.confirm);
        }
      });
    });

    if (!confirmed) {
      console.log('❌ 用户取消删除');
      return;
    }

    try {
      wx.showLoading({
        title: '删除中...',
        mask: true
      });

      // 删除指定索引的图片
      const newPhotos = this.data.editData.photos.filter((_, i) => i !== index);
      
      // 更新本地显示
      this.setData({
        'editData.photos': newPhotos
      });

      // 🔥 同步到服务器（参考Flutter的removeAlbumImage）
      const updateData = {
        userPhone: userData.userPhone,
        userImgUrls: newPhotos
      };

      await api.updateUserInfo(updateData);
      console.log('✅ 相册删除已同步到服务器');

      // 更新本地用户信息（保留 extraData）
      const updatedUserData = {
        ...userData,
        userImgUrls: newPhotos,
        // 🔥 确保 extraData（包含 openid）被保留
        extraData: {
          ...(userData.extraData || {}),
          openid: userData?.extraData?.openid || wx.getStorageSync('wx_openid')
        }
      };
      storage.saveUserInfo(updatedUserData);
      
      console.log('🔍 调试 deletePhoto - 保存的 openid:', updatedUserData.extraData?.openid);

      wx.hideLoading();
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });

    } catch (error) {
      wx.hideLoading();
      console.error('❌ 删除照片失败:', error);
      wx.showToast({
        title: '删除失败，请重试',
        icon: 'none'
      });
    }
  },

  // 保存编辑数据
  async saveEditData() {
    // 获取当前用户信息
    const userData = storage.getUserInfo();
    if (!userData) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    try {
      console.log('📝 =============== 开始保存用户信息 ===============');

      // 获取选中的爱好
      const selectedHobbies = this.data.hobbies
        .filter(item => item.selected)
        .map(item => item.name);

      // 构建更新数据（参考Flutter项目的实现）
      const updateData = {
        userPhone: userData.userPhone, // 必须参数
        username: this.data.editData.nickname,
        userGender: this.data.editData.gender,
        userAge: this.data.editData.age,
        userBirthday: this.data.editData.birthday,
        userSignature: this.data.editData.signature,
        userFrequentPlaces: this.data.editData.location,
        userHobbies: selectedHobbies,
        userAvatarUrl: this.data.editData.avatar,
        userImgUrls: this.data.editData.photos
      };

      console.log('📊 准备更新的数据:', updateData);

      // 调用API更新用户信息
      const response = await api.updateUserInfo(updateData);
      
      console.log('✅ 服务器更新成功:', response);

      // 更新本地用户信息
      const updatedUserData = {
        ...userData,
        username: this.data.editData.nickname,
        userAvatarUrl: this.data.editData.avatar,
        userGender: this.data.editData.gender,
        userAge: this.data.editData.age,
        userBirthday: this.data.editData.birthday,
        userSignature: this.data.editData.signature,
        userFrequentPlaces: this.data.editData.location,
        userHobbies: selectedHobbies,
        userImgUrls: this.data.editData.photos,
        // 🔥 确保 extraData（包含 openid）被保留
        extraData: {
          ...(userData.extraData || {}),
          openid: userData?.extraData?.openid || wx.getStorageSync('wx_openid')
        }
      };

      // 保存到本地存储
      storage.saveUserInfo(updatedUserData);

      console.log('✅ 本地用户信息已更新:', updatedUserData);
      console.log('🔍 调试 saveEditData - 保存的 extraData:', updatedUserData.extraData);
      console.log('🔍 调试 saveEditData - 保存的 openid:', updatedUserData.extraData?.openid);

      wx.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 1500,
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });

    } catch (error) {
      console.error('❌ 保存用户信息失败:', error);
      wx.showToast({
        title: '保存失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  }
});

